var express = require('express');
var router = express.Router();
const { exec } = require('child_process');
/* 模板
	'hosts.sunbeyond.com': {
		password: 'clk2kkrff'
		, path: '/data/Ed500fmC/sites/lipstick.phantasm.top/www/'
		// 针对不同 git 库的识别
		, gits: {
			gitee: {
				project: {
					id: 5778965
					, full_name: 'sunbeyond/thinkphp.lipstick'
					, url: 'https://gitee.com/sunbeyond/thinkphp.lipstick'
					, git_url: 'git://gitee.com/sunbeyond/thinkphp.lipstick.git'
				}
			}
		}
		// 事件对应的后续操作
		, events: {
			push: 'git pull'    // 仓库推送代码、推送 / 删除分支
			, tag_push: ''  // 新建 / 删除 tag
			, issue: '' // 新建任务、变更任务状态、更改任务指派人
			, pull_request: ''  // 新建、更新、合并、关闭 Pull Request
		}
	}
 */
const config = {
	'lipstick.phantasm.top': {
        password: '1&Gg21jhdis'
		, path: '/data/Ed500fmC/sites/lipstick.phantasm.top/www/'
        // 针对不同 git 库的识别
		, gits: {
            gitee: {
                project: {
                    id: 5778965
                    , full_name: 'sunbeyond/thinkphp.lipstick'
                    , url: 'https://gitee.com/sunbeyond/thinkphp.lipstick'
                    , git_url: 'git://gitee.com/sunbeyond/thinkphp.lipstick.git'
                }
            }
        }
        // 事件对应的后续操作
        , events: {
            push: 'git pull'
        }
	}
	, 'hosts.sunbeyond.com': {
        password: 'clk2kkrff'
		, path: '/data/VdNkEq6z/sites/hosts.sunbeyond.com/www/'
        // 针对不同 git 库的识别
		, gits: {
            gitee: {
                project: {
					id: 5849820
					, full_name: "sunbeyond/nodejs.hosts"
					, url: "https://gitee.com/sunbeyond/nodejs.hosts"
					, git_url: "git://gitee.com/sunbeyond/nodejs.hosts.git"
				}
            }
        }
        // 事件对应的后续操作
        , events: {
            push: 'git pull'
        }
	}
};

const status = {
    '0': { code: 0, msg: '成功' }
    , '10': { code: 10, msg: '没有接受到请求'}
    , '13': { code: 13, msg: 'exec执行错误'}
    , '20': { code: 20, msg: '密码不存在' }
    , '21': { code: 21, msg: '密码错误' }
    , '33': { code: 33, msg: 'git数据校验错误' }
    , '52': { code: 52, msg: '项目本地 path 不存在' }
    // , '53': { code: 53, msg: '项目本地对应的 event exec 不存在' }
    , '99': { code: 99, msg: '未知的异常错误' }
};

/* GET home page. */
router.get( '/', function( req, res, next ) {
    res.render(
        'index'
        , { title: 'WebHooks', content: '这个一款基于WebHook的事件处理应用' }
    );
} );

for ( let project in config ) {
    var { password, path, gits, events } = config[ project ]
        , body = null;  // 请求

    for ( let git in gits ) {

        for ( let event in events ) {
            // 跳过空的 event exec
            if ( !events[ event ] ) {
                continue;
            };

            // 注册router
            // project/git/event/
            router.post( `/${ project }/${ git }/${ event }`, function( req, res, next ) {
                body = req.body;

                // 是否有请求
            	if ( !body ) {
            		res.send( status[ 10 ] );
            		return false;
            	};

                if ( !body.password ) {
                    res.send( status[ 20 ] );
                    return false;
                };

                // 密码是否正确
                if ( password !== body.password ) {
                    res.send( status[ 21 ] );
                    return false;
                };

                // git 校验数据
                if ( !compare( body, gits[ git ] ) ) {
                    res.send( status[ 33 ] );
                    return false;
                };

                if ( !path ) {
                    res.send( status[ 52 ] );
                    return false;
                };

                exec( `cd ${ path } && ${ events[ event ] }`, ( error, stdout, stderr ) => {
    				// exec执行错误
    				if ( error ) {
                        res.send( Object.assign( {}, status[ 13 ], {
                            msg: error
                        } ) );
                        return false;
    				};

    				console.log( `stdout: ${ stdout }` );
    				console.log( `stderr: ${ stderr }` );

    				res.send( status[ 0 ] );
        		} );
            } );
        };
    };
};

// 比较一个对象是否等于另个对象
function compare( origin, target ) {
    if (typeof target === 'object')    {
        if (typeof origin !== 'object') return false
        for (let key of Object.keys(target))
            if (!compare(origin[key], target[key])) return false
        return true
    } else return origin === target
}

module.exports = router;
